import hashlib
import time as time_module  # 使用别名
from flask import request, make_response
import xml.etree.ElementTree as ET
from config_loader import load_config
from service.club_handler import alarms_today_club
from service.handler import handle_set_alarm_club, make_text_msg_club, handle_alarms_query

# 加载配置
cfg = load_config("config.yml")
WECHAT_TOKEN = cfg["WECHAT_TOKEN"]
TIP_EXAMPLE = cfg["TIP_EXAMPLE"]
PREFIX_STR = cfg["PREFIX_STR"]

# 用户状态和时间戳
user_state = {}
user_timestamp = {}
last_alarm_id = 0


# 微信公众号消息推送
def wechat_club_message():
    global last_alarm_id
    if request.method == 'GET':
        query = request.args
        signature = query.get('signature', '')
        timestamp = query.get('timestamp', '')
        nonce = query.get('nonce', '')
        echostr = query.get('echostr', '')
        s = [timestamp, nonce, WECHAT_TOKEN]
        s.sort()
        s = ''.join(s)
        if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:
            return make_response(echostr)
    elif request.method == 'POST':
        xml_str = request.data
        if not xml_str:
            return ''
        xml_tree = ET.fromstring(xml_str)
        content = xml_tree.find('Content').text
        msg_type = xml_tree.find('MsgType').text
        from_user = xml_tree.find('FromUserName').text
        to_user = xml_tree.find('ToUserName').text
        print(f'Received message: {content}')
        if from_user in user_timestamp and time_module.time() - user_timestamp[from_user] > 600:
            user_state[from_user] = 'normal'
        #################################### 闹钟消息设置处理 ###########################################
        reply_content = ''
        if content == '闹钟':
            reply_content = '💃💃请按下面格式设置💃💃' + chr(13) + PREFIX_STR + chr(13) + TIP_EXAMPLE
            user_state[from_user] = 'waiting_for_alarm'
            user_timestamp[from_user] = time_module.time()
            reply_content = make_text_msg_club(from_user, to_user, reply_content)
        elif user_state.get(from_user) == 'waiting_for_alarm' and content != '退出':
            reply_content = handle_set_alarm_club(from_user, to_user, content)
        elif user_state.get(from_user) == 'waiting_for_alarm' and content == '退出':
            reply_content = make_text_msg_club(from_user, to_user, 'OKOK')
            user_state[from_user] = 'normal'
        #################################### 打卡 | 抢购 | 地铁 ###########################################
        elif content == '抢购':  # 同时显示打卡和抢购数据
            reply_content = alarms_today_club(from_user, to_user, '抢购')
        elif content == '打卡':  # 只显示当天的打卡数据
            reply_content = alarms_today_club(from_user, to_user, '打卡')
        elif content == '地铁':  # 同时显示打卡和抢购数据
            reply_content = alarms_today_club(from_user, to_user, '地铁')
        else:
            reply_content = make_text_msg_club(from_user, to_user, '别说了，俺听不懂......')
        return reply_content
